<template>
  <el-card shadow="hover" class="mt-20">
    <!-- 表单校验流程2：给el-form绑定三个数据 -->
    <el-form
      label-width="100px"
      ref="spuFormRef"
      :model="spuFormData"
      :rules="spuFormRules"
    >
      <!-- 表单校验流程3：给el-form-item指定校验规则，prop -->
      <el-form-item label="SPU名称" prop="spuName">
        <!-- 表单校验流程4: 收集表单数据 -->
        <el-input placeholder="请输入SPU名称" v-model="spuFormData.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择品牌" v-model="spuFormData.tmId">
          <el-option
            v-for="tm in trademarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          placeholder="请输入SPU描述"
          :rows="3"
          v-model="spuFormData.description"
        />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="spuFormData.spuImageList"
          :action="`${BASE_URL}/admin/product/upload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :limit="MAX_UPLOAD_LIMIT"
          :on-exceed="handleExceed"
          accept="image/jpeg,image/png"
          :on-success="handleUploadSuccess"
        >
          <el-icon>
            <Plus />
          </el-icon>

          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible" width="30%">
          <img :src="dialogImageUrl" alt="预览图片" class="spu__img" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          :placeholder="baseSaleAttrPlaceholder"
          class="mr-10"
          v-model="selectedBaseSaleAttr"
        >
          <el-option
            v-for="baseSaleAttr in filteredBaseSaleAttrList"
            :key="baseSaleAttr.id"
            :label="baseSaleAttr.name"
            :value="`${baseSaleAttr.id}:${baseSaleAttr.name}`"
          />
        </el-select>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!selectedBaseSaleAttr"
          @click="addSaleAttr"
        >
          添加销售属性
        </el-button>
        <el-table :data="spuFormData.spuSaleAttrList" border class="mt-20">
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="60"
          />
          <el-table-column label="属性名" prop="saleAttrName" width="150" />
          <el-table-column label="属性值名称列表">
            <template v-slot="{ row }">
              <!-- key的值用index不太好，因为将来有删除操作 -->
              <el-tag
                type="success"
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.saleAttrValueName"
                class="mr-10"
                closable
                @close="delSpuSaleAttrValue(row.spuSaleAttrValueList, index)"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                size="small"
                v-if="row.isShowEdit"
                ref="inputRef"
                class="spu__input--w-150"
                v-model="saleAttrValueName"
                @blur="switchShow(row)"
                @keyup.enter="switchShow(row)"
              />
              <el-button
                size="small"
                :icon="Plus"
                v-else
                @click="switchEdit(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                :title="`您确定要删除 ${row.saleAttrName} 销售属性吗？`"
                @confirm="delSaleAttr($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    title="删除"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddOrUpdateSpu",
};
</script>

<script lang="ts" setup>
import { Plus, Delete } from "@element-plus/icons-vue";
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";
import { getAllTrademarkListApi } from "@/api/product/trademark";
import {
  getBaseSaleAttrListApi,
  addSpuApi,
  updateSpu,
  getSpuImageListApi,
  getSpuSaleAttrListApi,
} from "@/api/product/spu";
import type { TrademarkList } from "@/api/product/model/trademarkModel";
import type {
  BaseSaleAttrList,
  SpuFormData,
  SpuSaleAttrItem,
  SpuSaleAttrValueList,
  SpuSaleAttrList,
} from "@/api/product/model/spuModel";
import { useCategoryStore } from "@/stores/category";
import { useSpuStore } from "@/stores/spu";

const categoryStore = useCategoryStore();

// 保存
const submit = async () => {
  await spuFormRef.value.validate();

  const id = spuStore.spu.id;

  const data = {
    category3Id: categoryStore.category3Id,
    ...spuFormData,
    // 组件表单收集的到图片数据是 name，response.data
    // 而发送请求需要的图片数据是 imgName imgUrl
    spuImageList: spuFormData.spuImageList.map((img) => {
      return {
        imgName: img.name,
        // response是unknown，想要使用内部数据要用类型断言
        imgUrl: (img.response as { data: string }).data,
      };
    }),
  };

  if (id) {
    await updateSpu({
      ...data,
      id,
    });
  } else {
    await addSpuApi(data);
  }

  ElMessage.success(`${id ? "更新" : "添加"}SPU成功`);
  cancel();
};

// 获取数据
const trademarkList = ref<TrademarkList>([]);
const baseSaleAttrList = ref<BaseSaleAttrList>([]);

// 选项式API
// onMounted(async () => {
//   // Promise.allSettled([])
//   const res = await Promise.all([
//     getAllTrademarkListApi(),
//     getBaseSaleAttrListApi(),
//   ]);
//   trademarkList.value = res[0];
//   baseSaleAttrList.value = res[1];
// });

onMounted(async () => {
  trademarkList.value = await getAllTrademarkListApi();
});
onMounted(async () => {
  baseSaleAttrList.value = await getBaseSaleAttrListApi();
});

onMounted(async () => {
  // 只有更新需要请求，添加没有数据不需要请求
  const id = spuStore.spu.id as number;
  if (!id) return;
  // 组件el-upload需要的图片类型是UploadUserFile[]类型
  // 而我们发送请求添加SPU或从服务器获取SpuImageList的类型，都是{ imgName, imgUrl }类型
  const spuImageList = await getSpuImageListApi(id);

  // 将请求回来的{ imgName, imgUrl }类型变成组件需要的UploadUserFile[]类型
  spuFormData.spuImageList = spuImageList.map((img) => {
    return {
      name: img.imgName, // 必填
      url: img.imgUrl, // 图片地址（不填就渲染不了图片）
      response: {
        // 为了将来发送请求，可以得到图片地址
        data: img.imgUrl,
      },
    };
  });
});
onMounted(async () => {
  // 只有更新需要请求，添加没有数据不需要请求
  const id = spuStore.spu.id as number;
  if (!id) return;
  spuFormData.spuSaleAttrList = await getSpuSaleAttrListApi(id);
});

/*
  销售属性功能
  对baseSaleAttrList进行过滤，判断基础销售属性在不在spuSaleAttrList中
    在，过滤
    不在，保留
*/
// const filteredBaseSaleAttrList = computed(() => {
//   return baseSaleAttrList.value.filter((baseSaleAttr) => {
//     if (
//       spuFormData.spuSaleAttrList.some(
//         (spuSaleAttr) => spuSaleAttr.baseSaleAttrId === baseSaleAttr.id
//       )
//     ) {
//       // 在，过滤
//       return false;
//     }
//     // 不在，保留
//     return true;
//   });
// });

const filteredBaseSaleAttrList = computed(() =>
  baseSaleAttrList.value.filter(
    (baseSaleAttr) =>
      !spuFormData.spuSaleAttrList.some(
        (spuSaleAttr) => spuSaleAttr.baseSaleAttrId === baseSaleAttr.id
      )
  )
);

const selectedBaseSaleAttr = ref("");
// 添加销售属性
const addSaleAttr = () => {
  const [id, name] = selectedBaseSaleAttr.value.split(":");

  spuFormData.spuSaleAttrList.push({
    baseSaleAttrId: +id, // 基础销售属性id
    saleAttrName: name, // 基础销售属性的name
    spuSaleAttrValueList: [], // 销售属性值列表
    isShowEdit: false, // 编辑和显示切换的标识，默认显示显示模式
  });
  // 清空选中的值
  selectedBaseSaleAttr.value = "";
};
// 删除销售属性
const delSaleAttr = (index: number) => {
  spuFormData.spuSaleAttrList.splice(index, 1);
};

const baseSaleAttrPlaceholder = computed(() => {
  const length = filteredBaseSaleAttrList.value.length;
  return length ? `还剩 ${length} 个销售属性` : "没有啦";
});

// 编辑和显示模式
const inputRef = ref();

const isEditing = ref(false);

const switchEdit = async (row: SpuSaleAttrItem) => {
  if (isEditing.value) {
    ElMessage.warning("请完成之前的编辑");
    return;
  }
  isEditing.value = true;
  row.isShowEdit = true; // 显示编辑模式
  await nextTick();
  inputRef.value.focus();
};

// 销售属性值名称
const saleAttrValueName = ref("");

const switchShow = (row: SpuSaleAttrItem) => {
  if (
    row.spuSaleAttrValueList.some(
      (spuSaleAttrValue) =>
        spuSaleAttrValue.saleAttrValueName === saleAttrValueName.value
    )
  ) {
    ElMessage.warning("不同添加相同的属性值~");
    return;
  }

  isEditing.value = false;
  row.isShowEdit = false; // 切换显示模式

  if (!saleAttrValueName.value) return; // 如果输入内容为空，就不添加了

  row.spuSaleAttrValueList.push({
    // 添加数据
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: saleAttrValueName.value,
    // isChecked: "string",
    // saleAttrName: "string",
    // spuId: 0,
    // id: 0,
  });
  saleAttrValueName.value = ""; // 清空输入的值，将来下次添加值就是空了
};

const delSpuSaleAttrValue = (
  spuSaleAttrValueList: SpuSaleAttrValueList,
  index: number
) => {
  spuSaleAttrValueList.splice(index, 1);
};

// 上传图片功能
const BASE_URL = import.meta.env.VITE_API_URL;

// 预览图片
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

// 上传图片之前：限制图片大小和类型
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // rawFile 代表上传图片文件数据
  // rawFile.type 文件类型
  const fileTypes = ["image/jpeg", "image/png"];
  if (!fileTypes.includes(rawFile.type)) {
    ElMessage.error("上传图片只能是jpg或png格式!");
    // 返回false，上传失败（不会上传了）
    return false;
    // rawFile.size 文件大小，单位字节byte
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("图片大小不能超过200kb!");
    return false;
  }
  // 返回true，继续上传图片
  return true;
};

const MAX_UPLOAD_LIMIT = 10;

const handleExceed = () => {
  ElMessage.warning("图片最多上传xx张");
};

const isUploadHidden = computed(() => {
  return spuFormData.spuImageList.length < MAX_UPLOAD_LIMIT
    ? "inline-flex"
    : "none";
});
// 图片上传成功，清空校验错误信息
const handleUploadSuccess = () => {
  spuFormRef.value.clearValidate(["spuImageList"]);
};

const spuStore = useSpuStore();
// 表单校验流程1：定义三个数据
const spuFormRef = ref();
const spuFormData = reactive<SpuFormData>({
  spuName: spuStore.spu.spuName,
  tmId: spuStore.spu.tmId,
  description: spuStore.spu.description,
  spuImageList: [
    // {
    //   id: 0,
    //   imgName: "string",
    //   imgUrl: "string",
    //   spuId: 0,
    // },
  ],
  spuSaleAttrList: [
    // {
    //   baseSaleAttrId: 0, // 基础销售属性id
    //   id: 0,
    //   saleAttrName: "string", // 基础销售属性的name
    //   spuId: 0,
    //   spuSaleAttrValueList: [
    //     {
    //       baseSaleAttrId: 0,
    //       id: 0,
    //       isChecked: "string",
    //       saleAttrName: "string",
    //       saleAttrValueName: "string",
    //       spuId: 0,
    //     },
    //   ],
    // },
  ],
});

// 自定义校验规则函数，表单校验时触发
const spuSaleAttrListValidator = (
  rule: any,
  value: SpuSaleAttrList,
  callback: any
) => {
  /*
    rule 校验规则信息，包含规则名称等内容
    value 校验的数据
    callback 一个函数（必须要调用）
      callback() 表单校验通过
      callback(new Error('错误信息')) 表单校验失败，参数就是失败提示的错误信息
  */

  // 1. 销售属性必须有值
  if (!value.length) {
    callback(new Error("请至少添加一个销售属性"));
    return;
  }

  // 2. 每个销售属性的销售属性值列表至少添加一个销售属性值
  if (value.some((spuSaleAttr) => !spuSaleAttr.spuSaleAttrValueList.length)) {
    callback(new Error(" 每个销售属性请至少添加一个销售属性值"));
    return;
  }

  // 校验通过
  callback();
};

const spuFormRules = reactive({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请上传SPU图片" }],
  spuSaleAttrList: [
    {
      required: true, // 显示*号，同时也是必填项
      // 简单校验规则，没办法判断数组中数组数据是否有值，所以使用自定义校验规则
      validator: spuSaleAttrListValidator, // 自定义校验规则
    },
  ],
});

const emit = defineEmits(["setIsShow"]);

const cancel = () => {
  emit("setIsShow", 1);
};
</script>

<style scoped>
.spu__img {
  width: 100%;
}

:deep(.el-upload) {
  display: v-bind(isUploadHidden);
}

.spu__input--w-150 {
  width: 150px;
}
</style>
